import dayjs from 'dayjs';
import { isEmpty } from 'lodash-es';
import type { IUploadAuthTokenDetail } from '../interface';
import { decrypt, encrypt } from './crpt';

const UPLOADSTORAGEKEY = 'ym-video-upload-store-key';

export function getAuthToken(getUploadAuthTokenApi: () => Promise<any>) {
  let needGetUploadToken = false;
  let authTokenDetail = {} as IUploadAuthTokenDetail;
  let uploadCipherText = localStorage.getItem(UPLOADSTORAGEKEY) || '';

  if (!uploadCipherText) {
    needGetUploadToken = true;
  } else {
    authTokenDetail = decrypt(uploadCipherText) as IUploadAuthTokenDetail;
    if (
      isEmpty(authTokenDetail) ||
      dayjs(authTokenDetail.expiredTime).diff(dayjs()) < 5 * 60 * 1000
    ) {
      localStorage.removeItem(UPLOADSTORAGEKEY);
      needGetUploadToken = true;
    }
  }

  // 有效期 < 5分钟
  if (needGetUploadToken) {
    return getUploadAuthTokenApi().then((res) => {
      const tempAuthTokenDetail = res.data;
      uploadCipherText = encrypt(tempAuthTokenDetail);
      localStorage.setItem(UPLOADSTORAGEKEY, uploadCipherText);
      return Promise.resolve(tempAuthTokenDetail);
    });
  }

  return Promise.resolve(authTokenDetail);
}

//使用场景： 预览本地图片/视频
//方案1： window.URL.createObjectURL(file) 根据文件返回文件bolb的对象，该对象包含file的完整信息
//方案2： const reader = new FileReader();reader.readAsDataURL(file); reader.onload = () => {const base64 = reader.result;} 直接把 文件转为base64位码
export const getFileURL = (file: File) => {
  let getUrl = null;
  if (window.URL !== undefined) {
    //basic mozilla(firefox)
    getUrl = window.URL.createObjectURL(file);
  } else if (window.webkitURL !== undefined) {
    // webkit or chrome
    getUrl = window.webkitURL.createObjectURL(file);
  }
  return getUrl;
};
